<template>
  <div class="edit-area-container">
    <div class="header">
      <span class="title">编辑库区</span>
      <el-button class="back-btn" @click="goBack">返回</el-button>
    </div>
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="120px"
      class="edit-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属仓库：" prop="ckName" required>
            <el-select v-model="form.ckName" placeholder="请选择仓库">
              <el-option v-for="item in warehouseOptions" 
                        :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="tree-tip">
          
        </el-col>
        <el-col :span="12">
          <el-form-item label="库区名称：" prop="kuName" required>
            <el-input v-model="form.kuName"  show-word-limit placeholder="请输入库区名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="ku-tip">
          
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属温区：" prop="warmArea">
           <el-select v-model="form.warmArea" placeholder="请选择温区">
              <el-option 
                v-for="item in warmAreaOptions" 
                :key="item.value" 
                :label="item.label" 
                :value="item.label" />
         </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="库区备注：" prop="beizhu">
            <el-input
              v-model="form.beizhu"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
              placeholder="请输入库区备注"
            />
          </el-form-item>
          
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" class="submit-row">
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref ,onMounted} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ckname , warmArea, updateKU ,addKu} from "@/api/set/product.js";

const router = useRouter()
const route = useRoute()
const formRef = ref(null)

const form = ref({
  ckName: '',      // 所属仓库
  kuName: '',      // 库区名称
  warmArea: '',    // 所属温区
  beizhu: '',      // 备注
  id: '',          // 库区 ID（编辑时用）
})

// 下拉选项响应式
const warehouseOptions = ref([])
const warmAreaOptions = ref([])

// 表单校验规则
const rules = {
  ckName: [
    { required: true, message: '请选择所属仓库', trigger: 'change' },
  ],
  kuName: [
    { required: true, message: '请输入库区名称', trigger: 'blur' },
    { min: 1, max: 50, message: '库区名称长度为1-50字符', trigger: 'blur' },
  ],
  beizhuu: [
    { min: 1, max: 500, message: '备注长度为1-500字符', trigger: 'blur' },
  ],
}

//根据路由参数设置默认值
onMounted(async() => {
  // 获取仓库选项
  const ckRes = await ckname()
  warehouseOptions.value = (ckRes?.data || []).map(item => ({
    label: item.name,    //前端展示的值
    value: item.ckid      
  }))
  //获取温区选项
  const warRes=await warmArea()
  warmAreaOptions.value = (warRes?.data || []).map(item => ({
    label: item.warmArea,
    value: item.wid
  }))


  console.log('options:', warehouseOptions.value, warmAreaOptions.value)
  console.log('route.query:', route.query)

   // 自动填充跳转过来的数据（注意要赋id）
  form.value.ckName = route.query.ckName || ''
  form.value.warmArea = route.query.warmArea || ''
  form.value.kuName = route.query.kuName || ''       // 库区名
  form.value.id = route.query.id || ''

  console.log('form:', form.value)
})


// 返回按钮
function goBack() {
  router.back()
}

// 提交
async function handleSubmit() {
  const valid = await formRef.value.validate();
  if (valid) {
    console.log("执行更新");
    await gaiKU();
  }else {
    console.log("执行增加");
    await Addku();
  }
}

//增加
async function Addku() {
    try {
    const res = await addKu({
      ckName: form.value.ckName,           // 直接用id
      kuname: form.value.kuName,
      warmAreaName: form.value.warmArea,   // 直接用id
      beizhu: form.value.beizhu
    })
    if (res && res.code === 200) {
      ElMessage.success('新增库区成功')
      router.back()
    } else {
      ElMessage.error(res.msg || '新增失败')
    }
  } catch (error) {
    ElMessage.error('新增异常')
  }
}

// 更新库区信息
async function gaiKU() {
   console.log("更新操作，ID：", form.value.id, "类型：", typeof form.value.id);
  try {
    // 1. 类型转换与验证
    const id = parseInt(form.value.id, 10);
    console.log("强转后ID：", id, "类型：", typeof id);
    
    if (isNaN(id) || !id) {
      ElMessage.error('ID必须是有效的数字');
      return;
    }
    
    // 2. 构造参数
    const params = {
      id: id,
      caName: form.value.ckName,
      warmArea: form.value.warmArea,
      kuName: form.value.kuName,
      beizhu: form.value.beizhu
    };
    
    // 3. 打印完整请求信息（便于调试）
    console.log("请求参数：", params);
    console.log("请求路径及参数：", `/SAupda?${new URLSearchParams(params)}`);
    

    // 4. 调用接口
    const res = await updateKU(params);
      if (res && res.code === 200) { 
            ElMessage.success('更新成功');
          } else {
            ElMessage.error(res?.msg || '更新失败，请稍后重试');
          }
  } catch (error) {
    // 6. 详细错误信息展示
    console.error('更新失败详情：', error);
  
  }
}

</script>



<style scoped>
.edit-area-container {
  padding: 24px;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 6px;
  max-width: 900px;
  margin: 30px auto;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}
.title {
  font-size: 18px;
  font-weight: 600;
}
.back-btn {
  float: right;
}
.edit-form {
  margin-top: 10px;
}
.tree-tip {
  display: flex;
  align-items: center;
  height: 40px;
  padding-left: 10px;
}
.ku-tip {
  display: flex;
  align-items: center;
  height: 40px;
  padding-left: 10px;
  color: #888;
}
.remark-tip {
  color: #888;
  margin-top: -10px;
  margin-bottom: 10px;
  text-align: right;
}
.submit-row {
  margin-top: 20px;
  display: flex;
  align-items: center;
}
.submit-tip {
  margin-left: 16px;
  color: #888;
}
</style>